package com.example.comm.util;

import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class AreaTokenUtils {
    /**
     * 从请求中获取AreaToken
     *
     * @return
     */
    public static String getToken() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes == null) {
            return "";
        }
        HttpServletRequest request = requestAttributes.getRequest();
        return request.getHeader("AreaToken");
    }

    /**
     * 获取城市ID
     *
     * @return
     */
    public static String getCityId() {
        String areaToken = getToken();
        if (StringUtils.isEmpty(areaToken)) {
            return null;
        }
        Map<String, Object> areaInfoMap = BZJson.toMap(areaToken);
        if (ObjectUtils.isEmpty(areaInfoMap)) {
            return null;
        }
        if (areaInfoMap.containsKey("city_id")) {
            return areaInfoMap.get("city_id").toString();
        }
        return null;
    }

    /**
     * 获取省ID
     *
     * @return
     */
    public static String getProvinceId() {
        String areaToken = getToken();
        if (StringUtils.isEmpty(areaToken)) {
            return null;
        }
        Map<String, Object> areaInfoMap = BZJson.toMap(areaToken);
        if (ObjectUtils.isEmpty(areaInfoMap)) {
            return null;
        }
        if (areaInfoMap.containsKey("province_id")) {
            return areaInfoMap.get("province_id").toString();
        }
        return null;
    }

    /**
     * 获取地区ID
     *
     * @return
     */
    public static String getDistrictId() {
        String areaToken = getToken();
        if (StringUtils.isEmpty(areaToken)) {
            return null;
        }
        Map<String, Object> areaInfoMap = BZJson.toMap(areaToken);
        if (ObjectUtils.isEmpty(areaInfoMap)) {
            return null;
        }
        if (areaInfoMap.containsKey("district_id")) {
            return areaInfoMap.get("district_id").toString();
        }
        return null;
    }
}
